package cn.enilu.flash.api.controller.business;

import cn.enilu.flash.StatusEnum;
import cn.enilu.flash.api.controller.BaseController;
import cn.enilu.flash.bean.entity.front.Ids;
import cn.enilu.flash.bean.entity.front.School;
import cn.enilu.flash.bean.vo.business.SchoolVo;
import cn.enilu.flash.dao.MongoRepository;
import cn.enilu.flash.service.front.IdsService;
import cn.enilu.flash.utils.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

import static cn.enilu.flash.bean.vo.front.Rets.success;
import static cn.enilu.flash.utils.BeanUtil.copyProperties;


@RestController
@RequestMapping("/school")
public class SchoolController extends BaseController {

    @Autowired
    private MongoRepository mongoRepository;

    @Autowired
    private IdsService idsService;

    @PostMapping(value = "add")
    public Object add(@Valid @ModelAttribute SchoolVo schoolVo) {
        School school = new School();
        copyProperties(schoolVo, school);
        school.setSchool_id(idsService.getId(Ids.SCHOOL_ID));
        school.setStatus(StatusEnum.VALID.getValue());
        mongoRepository.save(school);

        return success();
    }

    @GetMapping(value = "/list")
    public Object list() {
        List<School> foods = mongoRepository.findAll(School.class);
        return success(foods);
    }

    @GetMapping(value = "/count")
    public Object count() {
        long count = mongoRepository.count("school");
        return success("count", count);
    }

    @GetMapping(value = "/{school_id}")
    public Object get(@PathVariable("school_id") Long id) {
        School food = mongoRepository.findOne(School.class, Maps.newHashMap("school_id", id));
        return success(food);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Object delete(@PathVariable("id") Long id) {
        School food = mongoRepository.findOne(School.class, Maps.newHashMap("school_id", id));
        food.setStatus(StatusEnum.INVALID.getValue());
        mongoRepository.update(food);
        return success();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(@ModelAttribute @Valid SchoolVo food) {
        School old = mongoRepository.findOne(School.class, "school_id", food.getSchoolId());

        old.setName(food.getName());
        old.setDesc(food.getDesc());
        old.setAddress(food.getAddress());

        mongoRepository.update(old);

        return success();
    }


}
